﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Common.Web.EnumBinder
{
    /// <summary>
    /// 枚举model绑定器
    /// </summary>
    public class EnumModelBinder : IModelBinder
    {
        /// <summary>
        /// 执行绑定
        /// </summary>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == ValueProviderResult.None || string.IsNullOrWhiteSpace(value.ToString()))
            {
                if (bindingContext.ModelMetadata.IsRequired)
                {
                    string stateMessage = bindingContext.ModelMetadata.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(bindingContext.ModelName);
                    bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, stateMessage);
                }
                return;
            }
            if (EnumDescriptor.TryParseTo(bindingContext.ModelType, value.ToString(), true, out object val))
            {
                bindingContext.Result = ModelBindingResult.Success(val);
            }
            else
            {
                string stateMessage = bindingContext.ModelMetadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(value.ToString());
                bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, stateMessage);
            }
            await Task.CompletedTask;
        }
    }
}
